import { RouterButton } from "@/components"
import { getCurrentTime } from '@/lib'
import styles from '../../styles/Product.module.css'

const API_HOST_URL = (process.env.NODE_ENV !== 'production') ? 'http://localhost:3000/api/products' : 'https://dummyjson.com/products';

const Card = ({item}:{item:any}) => {
  return (
    <div className={styles.card}>
      <p className={styles.brand}>{item.brand}</p>
      <div className={styles.title}>
        <span>{item.title}</span>
        <p>
          <span className={styles.price}>${item.price}</span>
          <span className={styles.discount}>&nbsp;({item.discountPercentage}%)</span>
        </p>
      </div>
      <p style={{marginTop: '.6rem'}}>{item.description}</p>
      {/* <img src={item.thumbnail} alt="" /> */}
      <ul style={{display: 'flex'}}>
      { item.images?.map((url:string, index:number) => (
        <img key={index} className={styles.image} src={url} alt="" />
      ))}
      </ul>
    </div>
  )
}

export default function Page (props:any) {
  return (
    <main>
      <h1>Posts List Page</h1>
      <h4>{props.dt}</h4>
      <RouterButton />
      <ul>
      { props.data.map((item:any, index:number) => (
        <Card key={index} item={item} />
      ))}
      </ul>
    </main>
  )
}

// export async function getStaticProps () {
export async function getServerSideProps (context:any) {
  const dt = getCurrentTime()
  console.log('server side', dt)
  const {req, res, params, query, ...rest } = context
  console.log({params, query, rest})
  // const response = await fetch('https://dummyjson.com/products')
  const response = await fetch(`${API_HOST_URL}`)
  const reply = await response.json()
  console.log(reply)
  // console.log('cookie', req.headers.cookie)
  // res.setHeader('Set-Cookie', 'token=xxxxxxx')
  return ({
    props: {
      dt,
      data: reply.products
    }
  })
}
